<template>
	<view class="wrap">
		<u-navbar title="创建群聊">
			<view slot="right" class="u-m-r-30 cu-btn" :class="{'bg-blue':chosen.length}" @tap="create">
				确认{{chosen.length?`(${chosen.length})`:''}}
			</view>
		</u-navbar>
		<u-sticky>
			<view class="bg-white u-p-x-30 u-p-y-14 solid-bottom">
				<u-search v-model="key" placeholder="搜索好友名称" :show-action="false"></u-search>
			</view>
		</u-sticky>
		<u-index-list :scrollTop="scrollTop" :sticky="false" :index-list="indexList">
			<view v-for="(value,key) in users" :key="key">
				<u-index-anchor :index="key" />
				<view class="u-flex u-p-x-30 u-p-y-20 bg-white u-border-bottom" 
					v-for="(user,index) in value" 
					:key="index"
					@tap="pickUser(user)">
					<view class="checkbox u-m-r-30 shrink-0" :class="{checked:user.checked}">
					</view>
					<u-avatar :src="user.avatarUrl" mode="square" class="shrink-0"></u-avatar>
					<text class="u-m-l-20 u-font-34">{{user.remarks||user.userName}}</text>
				</view>
			</view>
		</u-index-list>
		<u-modal
			:value="prompt.show"
			title="群聊名称" 
			showCancelButton
			@cancel="reject"
			@confirm="resolve"
		>
			<view class="u-m-y-20 u-m-x-30 bg-gray u-p-20 radius">
				<input class="u-font-28" v-model="prompt.content" maxlength="30" placeholder="设置名称(30字内)" />
			</view>
		</u-modal>
	</view>
</template>

<script>
	import {delay, toast} from "@/utils/util.js"
	import {matching} from '@/utils/pinyin.js'
	import {createGroup} from "@/api/addr.js"
	import {mapGetters,mapActions} from "vuex"
	import { ConversationType } from "@/entity/ConversationType"
	export default {
		data() {
			return {
				scrollTop: 0,
				chosen:[],
				key:'',
				prompt:{
					show:false,
					content:''
				},
				bridge:null,
				lock:false
			};
		},
		computed:{
			...mapGetters('addr',['friends']),
			users(){
				const res = this.friends.reduce((res,item)=>{
					if(!item.userName.includes(this.key)&&!item.remarks.includes(this.key)&&!item.userNum.includes(this.key)){
						return res
					}
					const firstChar = item.remarks.slice(0,1)||item.userName.slice(0,1)
					let letter = ''
					if(/[a-zA-z]/.test(firstChar)){
						letter=firstChar
					}else{
						const py = matching(firstChar)
						letter = !!py?py.slice(0,1):'#'
					}
					letter = letter.toUpperCase()
					if(!res[letter]){
						res[letter] = []
					}
					res[letter].push({
						...item,
						checked:this.chosen.some((id)=>id==item.userId)
					})
					return res
				},{})
				return Object.entries(res).sort(([[next]],[[pre]])=>{
					if(pre=='#'){
						return -1
					}else if(next=='#'){
						return 1
					}else{
						return next.charCodeAt()-pre.charCodeAt()
					}
				}).reduce((r,[key,value])=>{
					r[key]=value
					return r
				},{})
			},
			indexList(){
				return Object.keys(this.users).sort((next,pre)=>{
					if(pre=='#'){
						return -1
					}else if(next=='#'){
						return 1
					}else{
						return next.charCodeAt()-pre.charCodeAt()
					}
				})
			}
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		methods:{
			...mapActions('addr',['fetchAllgroups']),
			...mapActions('chat', ['setConversation']),
			resolve(e){
				this.bridge&&this.bridge.resolve&&this.bridge.resolve(e)
			},
			reject(e){
				this.bridge&&this.bridge.reject&&this.bridge.reject(e)
			},
			pickUser(user){
				if(user.checked){
					this.chosen = this.chosen.filter((item)=>item!=user.userId)
				}else{
					this.chosen.push(user.userId)
				}
			},
			async create(){
				if(!this.chosen.length){
					return
				}
				await new Promise((resolve,reject)=>{
					this.bridge={
						resolve:()=>{
							if(!this.prompt.content){
								return toast('请输入群名称')
							}
							resolve()
							this.prompt.show = false
						},
						reject:()=>{
							reject()
							this.prompt.show = false
						}
					}
					this.prompt.show = true
					this.prompt.content = ""
				})
				if(this.lock){
					throw new Error('正在请求中')
				}
				try{
					this.lock = true
					uni.showLoading({
						title:'loading...'
					})
					const info = await createGroup({name:this.prompt.content,userList:this.chosen})
					this.fetchAllgroups()
					await this.setConversation({
						id:info.id,
						type:ConversationType.Group,
						avatar:info.avatar,
						name:info.name
					})
					uni.redirectTo({
						url:`/pages/room/multi?id=${info.id}`
					})
				}catch(e){
					if(e.retCode=='10022'){
						toast(`${e.retDesc}，不是你的好友`)
					}else{
						toast(e.retDesc)
					}
					await delay(1000)
				}finally{
					this.lock = false
					uni.hideLoading()
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.wrap{
		min-height: 100vh;
	}
	.shrink-0{
		flex-shrink: 0;
	}
	.checkbox{
		width: 40rpx;
		height: 40rpx;
		background-color: $u-type-info-light;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
		transition: all 0.2s ease-out;
		&::after{
			font-family: "cuIcon";
			content: "\e645";
			color: #FFFFFF;
			opacity: 0;
			transition: all 0.2s ease-out;
		}
		&.checked{
			background-color: $u-type-primary;
			&::after{
				opacity: 1;
			}
		}
	}
</style>
